<template>
  <!-- 你的页面内容 -->
   <!-- <el-button type="primary" @click="initiateOAuthFlow">获取授权</el-button> -->
</template>

<script setup>
import { onMounted, ref,onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import CryptoJS from 'crypto-js'
import { useUserStore } from '../../stores/user'
import axios from 'axios'
import router from '../../router'

const userStore = useUserStore()
const cozeTokenData = ref({});

// 配置参数（需要替换为coze.cn的官方配置）
const config = {
  clientId: '59913591726407385069430754498653.app.coze',
  authorizationEndpoint: 'https://www.coze.cn/api/permission/oauth2/authorize',
  tokenEndpoint: 'https://api.coze.cn/api/permission/oauth2/token',
  redirectUri: 'http://localhost:5173/aiDo/callback', // 必须和注册的redirect_uri一致
  state: 'zhishekao' // 根据实际需求修改
}

// Token 管理相关变量
let refreshTimeout = null
let isRefreshing = false
let failedQueue = []

// 生成 PKCE 相关参数
const generatePKCE = async () => {
  const codeVerifier = CryptoJS.lib.WordArray.random(64).toString(CryptoJS.enc.Base64)
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '')
  
  const codeChallenge = CryptoJS.SHA256(codeVerifier)
    .toString(CryptoJS.enc.Base64)
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '')
  
  return { codeVerifier, codeChallenge }
}

// Token 存储管理
const storeTokens = (response) => {
  const { access_token, refresh_token, expires_in } = response
  const expiresAt = Date.now() + (expires_in * 1000)
  
  userStore.setCozeToken(response);
  
  setupTokenRefresh(expires_in)
}

// 设置自动刷新定时器
const setupTokenRefresh = (expiresIn) => {
  // 清除现有定时器
  if (refreshTimeout) clearTimeout(refreshTimeout)
  
  // 在过期前5分钟刷新
  const refreshBuffer = 800000 // 2分钟
  const delay = expiresIn * 1000 - refreshBuffer
  
  refreshTimeout = setTimeout(() => {
    refreshToken()
  }, delay > 0 ? delay : 0)
}

// Token 刷新逻辑
const refreshToken = async () => {
  if (isRefreshing) {
    return
    // return new Promise((resolve) => {
    //   failedQueue.push(resolve)
    // })
  }
  console.log("刷新token")
  isRefreshing = true
  

  try {
    const response = await axios.post(config.tokenEndpoint, JSON.stringify({
      client_id: config.clientId,
      grant_type: 'refresh_token',
      refresh_token: cozeTokenData.value.refresh_token
    }), {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    storeTokens(response.data)
    // 重试队列中的请求
    //failedQueue.forEach(promise => promise())
    //failedQueue = []
    
    // return Promise.resolve(response.data.access_token)
  } catch (error) {
    console.error('Token refresh failed:', error)
    clearAuth()
    //router.push('/login')
    return Promise.reject(error)
  } finally {
    isRefreshing = false
  }
}

// 初始化授权流程
const initiateOAuthFlow = async () => {
  const { codeVerifier, codeChallenge } = await generatePKCE()
  
  // 存储 codeVerifier 用于后续交换token
  sessionStorage.setItem('code_verifier', codeVerifier)
  
  // 构建授权URL
  const authUrl = new URL(config.authorizationEndpoint)
  authUrl.searchParams.append('client_id', config.clientId)
  authUrl.searchParams.append('redirect_uri', config.redirectUri)
  authUrl.searchParams.append('response_type', 'code')
  authUrl.searchParams.append('state', config.state)
  authUrl.searchParams.append('code_challenge', codeChallenge)
  authUrl.searchParams.append('code_challenge_method', 'S256')
  
  // 跳转到授权页面
  window.location.href = authUrl.toString()
}

// 清除认证信息
const clearAuth = () => {
  // userStore.setCozeToken({})
  // sessionStorage.removeItem('code_verifier')
  if (refreshTimeout) clearTimeout(refreshTimeout)
}

// 检查 Token 是否有效
const isTokenValid = () => {
  
  const expiresAt = cozeTokenData.value.expires_in
  console.log("检测token是否过期",Date.now() < parseInt(expiresAt*1000 || 0))
  return Date.now() > parseInt(expiresAt*1000 || 0)
}



// 处理回调
const handleCallback = async () => {
  const route = useRoute()
  
  // 检查错误
  if (route.query.error) {
    console.error('Authorization failed:', route.query.error)
    return
  }
  
  // 获取授权码
  const code = route.query.code
  if (!code) return

  try {
    // 获取存储的 code_verifier
    const codeVerifier = sessionStorage.getItem('code_verifier')
    
    // 交换token
    const response = await fetch(config.tokenEndpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        client_id: config.clientId,
        code,
        redirect_uri: config.redirectUri,
        grant_type: 'authorization_code',
        code_verifier: codeVerifier
      })
    })

    const tokenData = await response.json()
    
    // 存储token（根据实际需求调整存储方式）
    userStore.setCozeToken(tokenData);
    //sessionStorage.setItem('access_token', tokenData.access_token)
    sessionStorage.removeItem('code_verifier')
    router.push({path:"/aiDo"})
    console.log('OAuth flow completed successfully')
    
  } catch (error) {
    console.error('Token exchange failed:', error)
  }
}

// 页面加载时检查是否在回调路由
onMounted(() => {
  console.log(window.location.pathname)
  if (window.location.pathname === '/aiDo/callback') { //回调使用
    handleCallback()
  }else{ //初始授权使用
    if(!cozeTokenData.access_token){
      initiateOAuthFlow()
    }
    
  }

  // 页面可见性变化时检查 Token
  document.addEventListener('visibilitychange', () => {
    console.log("显示页面")
    cozeTokenData.value = userStore.getCozeToken()
    refreshToken()
    if (document.visibilityState === 'visible' && !isTokenValid()) {
      console.log("显示页面2")
      refreshToken()
    }
  })

})

onBeforeUnmount(() => {
  document.removeEventListener('visibilitychange', () => {})
})
</script>